﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;

using NUnit.Framework;
using Lucene.Net.Index;
using Lucene.Net.Store;
using System.IO;
using Lucene.Net.Analysis.PanGu;
using Lucene.Net.Documents;
using PanGu;
using Lucene.Net.Search;
using Lucene.Net.QueryParsers;
using System.Diagnostics;

namespace SolrExample.Tests.Lucene
{
    /// <summary>
    /// Summary description for UnitTest1
    /// </summary>
    [TestFixture]
    public class UnitTest1
    {
        private static readonly string indexPath = @"C:\luceneIndex";
        [TestFixtureSetUp]
        public void InitializeAllTests()
        {

        }

        [Test]
        public void Test1()
        {   
            FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NativeFSLockFactory());
            bool isUpdate = IndexReader.IndexExists(directory);//判断索引库是否存在
            Console.WriteLine("索引库存在状态："+isUpdate);
            if (isUpdate)
            {
                //如果索引目录被锁定（比如索引过程中程序异常退出），则首先解锁
                //Lucene.Net在写索引库之前会自动加锁，在close的时候会自动解锁
                //不能多线程执行，只能处理意外被永远锁定的情况
                if (IndexWriter.IsLocked(directory))
                {
                    IndexWriter.Unlock(directory);//un-否定。强制解锁
                }
            }

            IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), !isUpdate, IndexWriter.MaxFieldLength.UNLIMITED);
            
            luceneExample example = new luceneExample() {
                id = "1",
                title = "长春市长春药店 i'm chinese people",
                content = "中华人民共和国 gdc",
                createdTime = DateTime.Now
            };
            int writerCount = AddDocument(example, writer);
            Console.WriteLine(writerCount);

            writer.Optimize();  //优化索引
            writer.Close();
            directory.Close();  //不要忘了Close，否则索引结果搜不到
        }

        private static int AddDocument(luceneExample example, IndexWriter writer)
        {
            writer.DeleteDocuments(new Term("id", example.id));
            Document document = new Document();
            try
            {                
                document.Add(new Field("id", example.id, Field.Store.YES, Field.Index.NOT_ANALYZED));//每个Document可以有自己的属性（字段），所有字段名都是自定义的，值都是string类型
                //Field.Store.YES不仅要对文章进行分词记录，也要保存原文，就不用去数据库里查一次了
                //需要进行全文检索的字段加 Field.Index. ANALYZED
                document.Add(new Field("title", example.title, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
                document.Add(new Field("contents", example.content, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
                document.Add(new Field("time", example.createdTime.ToString("yyyyMMdd"), Field.Store.YES, Field.Index.UN_TOKENIZED));

                writer.AddDocument(document);//把文档写入索引库 

                return writer.DocCount();
            }
            catch (Exception ex) {
                throw;
            }
        }

        [Test]
        public void Test2() {
            int recCount;
            string query = "长春";

            var searchTimer = Stopwatch.StartNew();
            IList<luceneExample> exampleList = Search(indexPath, query, 10, 1, out recCount);
            searchTimer.Stop();
            Console.WriteLine("Timer:" + searchTimer.Elapsed + "ms");

            foreach (luceneExample example in exampleList)
            {
                Console.WriteLine();
                Console.WriteLine(string.Format("id: {0}", example.id));
                Console.WriteLine(string.Format("title: {0}", example.title));
                Console.WriteLine(string.Format("content: {0}", example.content));
                Console.WriteLine(string.Format("createdTime: {0}", example.createdTime));
            }
        }

        public static List<luceneExample> Search(String indexDir, String q, int pageLen, int pageNo, out int recCount)
        {
            string keywords = q;

            IndexSearcher search = new IndexSearcher(indexDir);
            q = GetKeyWordsSplitBySpace(q, new PanGuTokenizer());
            QueryParser queryParser = new QueryParser("contents", new PanGuAnalyzer(true));
            Query query = queryParser.Parse(q);

            QueryParser titleQueryParser = new QueryParser("title", new PanGuAnalyzer(true));
            Query titleQuery = titleQueryParser.Parse(q);

            //构建复合查询的Query
            BooleanQuery bq = new BooleanQuery();
            bq.Add(query, BooleanClause.Occur.SHOULD);  //or
            bq.Add(titleQuery, BooleanClause.Occur.SHOULD);

            Hits hits = search.Search(bq);

            List<luceneExample> result = new List<luceneExample>();

            recCount = hits.Length();
            int i = (pageNo - 1) * pageLen;

            while (i < recCount && result.Count < pageLen)
            {
                luceneExample news = null;

                try
                {
                    news = new luceneExample();
                    news.id = hits.Doc(i).Get("id");
                    news.title = hits.Doc(i).Get("title");
                    news.content = hits.Doc(i).Get("contents");                    
                    String strTime = hits.Doc(i).Get("time");
                    news.createdTime = DateTime.ParseExact(strTime, "yyyyMMdd", null);


                    PanGu.HighLight.SimpleHTMLFormatter simpleHTMLFormatter =
                        new PanGu.HighLight.SimpleHTMLFormatter("<font color=\"red\">", "</font>");

                    PanGu.HighLight.Highlighter highlighter =
                        new PanGu.HighLight.Highlighter(simpleHTMLFormatter,
                        new Segment());

                    highlighter.FragmentSize = 50;

                    //news.Abstract = highlighter.GetBestFragment(keywords, news.Content);
                    //news.TitleHighLighter = highlighter.GetBestFragment(keywords, news.Title);
                    //if (string.IsNullOrEmpty(news.TitleHighLighter))
                    //{
                    //    news.TitleHighLighter = news.Title;
                    //}
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                finally
                {
                    result.Add(news);
                    i++;
                }
            }

            search.Close();
            return result;
        }

        static public string GetKeyWordsSplitBySpace(string keywords, PanGuTokenizer ktTokenizer)
        {
            StringBuilder result = new StringBuilder();

            ICollection<WordInfo> words = ktTokenizer.SegmentToWordInfos(keywords);

            foreach (WordInfo word in words)
            {
                if (word == null)
                {
                    continue;
                }

                result.AppendFormat("{0}^{1}.0 ", word.Word, (int)Math.Pow(3, word.Rank));
            }

            return result.ToString().Trim();
        }

        [TestFixtureTearDown]
        public void CleanupAllTests() { }
        
    }

    public class luceneExample {
        public string id { get; set; }
        public string title { get; set; }
        public string content { get; set; }
        public DateTime createdTime { get; set; }
    }
}
